<?php

namespace application\admin\controllers;


use mz\ars\Category;
use Yii;
use mz\ars\Article;
use mz\controllers\AdminController as Controller;

class ArticleController extends Controller
{
    # 文章列表
    public function actionIndex()
    {
        $list = Article::getAllArticle();
        return $this->render('index',compact('list'));
    }

    # 添加 编辑 文章
    public function actionAdd()
    {
        $id = intval(Yii::$app->request->get("id",0));
        $articleInfo = Article::getFindOne($id);
        $article = empty($id) ? [] : $articleInfo;
        $cate = Category::getAllCategory();
        return $this->render('add',compact('article','cate'));
    }

    # 编辑 | 添加保存动作
    public function actionSave()
    {
        if (!Yii::$app->request->isAjax) return $this->ajaxReturn(['e' => '2','m' => '请使用正确的请求方式']);
        $params = Yii::$app->request->post();
        $saveData = array_filter($params,function($key){
            return in_array($key , ['id','title','thumb','category_id','desc','content']);
        },ARRAY_FILTER_USE_KEY);

        $saveData['last_change'] = time();
        $saveData['created_uid'] = Yii::$app->admin->id;

        $model = !empty($saveData['id']) ? Article::findOne(['id' => $saveData['id']]) : new Article();
        $model->attributes = $saveData;
        # 数据验证
        if (!$model->validate()){
            var_dump($model->getErrors());
            return $this->ajaxReturn(['e' => 1,'m' => "很遗憾，数据验证失败！"]);
        }
        # 执行保存
        $msg = $model->save() ? ['e' => 0,'m' => "恭喜您，文章添加成功！"] : ['e' => '1','很遗憾，文章添加失败'];
        return $this->ajaxReturn($msg);
    }

    # 删除分类
    public function actionDelete()
    {

        if (!Yii::$app->request->isAjax) return $this->ajaxReturn(['e' => '2','m' => '请使用正确的请求方式']);
        $id = intval(Yii::$app->request->post('id',0));
        if (empty($id))return $this->ajaxReturn(['e' => '1','m' => "参数错误"]);
        $model = Article::findOne(['id' => $id]);
        if (empty($model))return $this->ajaxReturn(['e' => '1','m' => '您删除的文章不存在']);

        $model->attributes = ['id' => $id,'isdel' => 1];

        $msg = $model->save() ? ['e' => '0','m' => '恭喜您，分类删除成功'] : ['e' => '1','m' => '很遗憾，添加失败'];

        return $this->ajaxReturn($msg);
    }
}